package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Comment;
import com.tanhua.mongo.Publish;
import com.tanhua.mongo.Video;
import com.tanhua.template.OssTemplate;
import com.tanhua.uti.RelativeDateFormat;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.PublishVo;
import com.tanhua.vo.UserHolder;
import com.tanhua.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
public class QuanZiService {


    @Reference
    private PublishApi publishApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private CommentApi commentApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public ResponseEntity publishMovements(Publish publish, MultipartFile[] imageContent) throws IOException {
        publish.setUserId(UserHolder.getUser().getId());
        List<String> medias = new ArrayList<>();
        if (imageContent != null) {
            for (MultipartFile multipartFile : imageContent) {
                String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                medias.add(upload);
            }
            publish.setMedias(medias);
        }
        publish.setUserId(UserHolder.getUser().getId());
        publish.setState(0); //未审核

        String publishId = publishApi.save(publish);
        //做审核（华为云）==rockerMq
        rocketMQTemplate.convertAndSend("tanhua-quanzi", publishId);
        System.out.println("发送消息");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findAlbumByPage(Integer pageNum, Integer pageSize, Long userId) {
        PageBeanVo pageBeanVo = publishApi.findAlbumByPage(pageNum, pageSize, userId);
        List<PublishVo> publishVoList = new ArrayList<>();
        List<Publish> publishList = (List<Publish>) pageBeanVo.getItems();
        if (publishList.size() != 0) {
            //根据yonghuid查询userinfo
            UserInfo userInfo = userInfoApi.findByUserId(userId);
            for (Publish publish : publishList) {
                PublishVo publishVo = new PublishVo();
                //封装用户数据
                publishVo.setUserInfo(userInfo);
                //封装动态数据
                publishVo.setPublish(publish);

                //告知app当前动态是否被点过赞 如果点赞了就会显示高亮 如果没点赞就不显示高亮
                Boolean flag = stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUser().getId(), publish.getId()));
                if (flag) {
                    publishVo.setHasLiked(1); //点赞过 要高亮
                } else {
                    publishVo.setHasLiked(0); //没点赞过 不高亮
                }
                publishVoList.add(publishVo); // 加入到集合中
            }
        }
        // 6、设置vo到分页中
        pageBeanVo.setItems(publishVoList);
        // 7、返回分页
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findTimeLineByPage(Integer pageNum, Integer pageSize) {
        Long userId = UserHolder.getUser().getId();
        PageBeanVo pageBeanVo = publishApi.findTimeLineByPage(pageNum, pageSize, userId);
        List<PublishVo> publishVoList = new ArrayList<>();
        List<Publish> publishList = (List<Publish>) pageBeanVo.getItems();
        if (publishList.size() != 0) {


            for (Publish publish : publishList) {
                //根据用户id查询userinfo
                UserInfo userInfo = userInfoApi.findByUserId(publish.getUserId());
                PublishVo publishVo = new PublishVo();
                //封装用户数据
                publishVo.setUserInfo(userInfo);

                //封装动态数据
                publishVo.setPublish(publish);

                publishVoList.add(publishVo); // 加入到集合中
            }
        }
        // 6、设置vo到分页中
        pageBeanVo.setItems(publishVoList);
        // 7、返回分页
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findRecommendPublish(Integer pageNum, Integer pageSize) {
        //PageBeanVo pageBeanVo = publishApi.findRecommendByPage(pageNum, pageSize, UserHolder.getUser().getId());
        //大数据推荐的
        PageBeanVo pageBeanVo = fromRedisBigData(pageNum, pageSize, UserHolder.getUser().getId());

        List<PublishVo> voList = new ArrayList<>();
        List<Publish> publishList = (List<Publish>) pageBeanVo.getItems();

        if (CollectionUtil.isNotEmpty(publishList)) {
            for (Publish publish : publishList) {
                PublishVo vo = new PublishVo();

                // 2、userInfo封装vo
                UserInfo userInfo = userInfoApi.findByUserId(publish.getUserId());
                vo.setUserInfo(userInfo);

                // 3、publish封装vo
                vo.setPublish(publish);

                Boolean flag = stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUser().getId(), publish.getId()));
                if (flag) {
                    vo.setHasLiked(1); //点赞过 要高亮
                } else {
                    vo.setHasLiked(0); //没点赞过 不高亮
                }
                Boolean flag2 = stringRedisTemplate.hasKey(StrUtil.format("publish_love_comment_{}_{}", UserHolder.getUser().getId(), publish.getId()));
                if (flag2) {
                    vo.setHasLoved(1); //喜欢过 要高亮
                } else {
                    vo.setHasLoved(0); //没喜欢过 不高亮
                }
                // 6、将vo添加到集合中
                voList.add(vo);
            }
        }

        // 7、将voList添加到pageBean中
        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity likePublish(String publishId) {
        //封装comment
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUser().getId());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setPubType(1);
        Integer count = commentApi.save(comment);

        //记录到redis里面(设置"1"表示已经点赞，用于高亮显示)
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUser().getId(), publishId), "1");
        return ResponseEntity.ok(count);
    }

    public ResponseEntity unlikePublish(String publishId) {
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setPubType(1);
        comment.setUserId(UserHolder.getUser().getId());
        //redis删除
        stringRedisTemplate.delete(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUser().getId(), publishId));
        Integer count = commentApi.remove(comment);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity LovePublish(String publishId) {

        //封装comment
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUser().getId());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);
        comment.setPubType(1);
        Integer count = commentApi.save(comment);

        //记录到redis里面(设置"1"表示已经点赞，用于高亮显示)
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_love_comment_{}_{}", UserHolder.getUser().getId(), publishId), "1");
        return ResponseEntity.ok(count);
    }

    public ResponseEntity unLovePublish(String publishId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);
        comment.setPubType(1);
        comment.setUserId(UserHolder.getUser().getId());
        //redis删除
        stringRedisTemplate.delete(StrUtil.format("publish_love_comment_{}_{}", UserHolder.getUser().getId(), publishId));
        Integer count = commentApi.remove(comment);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity findPublishVoById(String publishId) {
        // 根据动态id查询publish
        Publish publish = publishApi.findPublishById(publishId);
        // 查询userInfo
        UserInfo userInfo = userInfoApi.findByUserId(publish.getUserId());
        // 组装publishVo
        PublishVo publishVo = new PublishVo();
        publishVo.setUserInfo(userInfo);
        publishVo.setPublish(publish);
        System.out.println(publishVo);
        return ResponseEntity.ok(publishVo);
    }

    public void toBigDate(int type, String publishId) {
        Map map = new HashMap<>();
        map.put("type", type);
        map.put("userId", UserHolder.getUser().getId());

        //根据publishId获取publish对象
        Publish publish = publishApi.findPublishById(publishId);
        map.put("pid", publish.getPid());
        rocketMQTemplate.convertAndSend("tanhua-bigdata", map);
    }


    //从redis中拿到大数据给推荐的数据
    private PageBeanVo fromRedisBigData(Integer page, Integer pagesize, Long userId) {

        String value = stringRedisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + userId);
        if (value == null) {
            return null;
        }
        String[] pids = value.split(",");
        Integer count = pids.length; //总条数
        //redis分页

        int start = (page - 1) * pagesize;
        if (start > count) {
            return null;
        }


        int end = page * pagesize;
        if (end > count) {
            end = count;
        }

        List<Publish> publishList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            Publish publish = publishApi.findByPid(pids[i]);
            publishList.add(publish);
        }
        return new PageBeanVo(page, pagesize, count.longValue(), publishList);
    }
}
